﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Data;
using System.IO;

namespace eBlog.Common.Files
{
    public class XmlHelper
    {
        protected string strXmlFile;
        protected XmlDocument objXmlDoc = new XmlDocument();

        /// <summary>
        /// 初始化xml操作类,XmlFile需要绝对路径Server.MapPath(),若文件不存在自动创建
        /// </summary>
        /// <param name="XmlFile"></param>
        public XmlHelper(string XmlFile)
        {
            try
            {
                if (!File.Exists(XmlFile))
                {
                    CreatXmlFile(XmlFile);
                   
                }
                objXmlDoc.Load(XmlFile);

            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            strXmlFile = XmlFile;
        }


        public void CreatXmlFile(string file)
        {
            XmlTextWriter writer = new
            XmlTextWriter(file, Encoding.UTF8);
            // start writing!
            writer.WriteStartDocument();
            writer.WriteStartElement("Root");
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        public void Save()
        {
            //保存文件。 
            try
            {
                objXmlDoc.Save(strXmlFile);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            objXmlDoc = null;
        }


         /// <summary>
         /// 更新节点内容
         /// </summary>
         /// <param name="xmlPathNode"></param>
         /// <param name="content"></param>
         public void Replace(string xmlPathNode, string content)
         {
             //更新节点内容。 
// ReSharper disable PossibleNullReferenceException
             if (xmlPathNode != null) objXmlDoc.SelectSingleNode(xmlPathNode).InnerText = content;
// ReSharper restore PossibleNullReferenceException
         }

        /// <summary>
         /// 删除一个节点
         /// </summary>
         /// <param name="node"></param>
         public void Delete(string node)
         {
             //删除一个节点。 
             string mainNode = node.Substring(0, node.LastIndexOf("/"));
             objXmlDoc.SelectSingleNode(mainNode).RemoveChild(objXmlDoc.SelectSingleNode(node));
         }
         /// <summary>
         /// 插入一个节点和此节点的一子节点
         /// </summary>
         /// <param name="MainNode"></param>
         /// <param name="ChildNode"></param>
         /// <param name="Element"></param>
         /// <param name="Content"></param>
         public void InsertNode(string MainNode, string ChildNode, string Element, string Content)
         {
             //插入一个节点和此节点的一子节点。 
             XmlNode objRootNode = objXmlDoc.SelectSingleNode(MainNode);
             XmlElement objChildNode = objXmlDoc.CreateElement(ChildNode);
             objRootNode.AppendChild(objChildNode);
             XmlElement objElement = objXmlDoc.CreateElement(Element);
             objElement.InnerText = Content;
             objChildNode.AppendChild(objElement);
         }
         /// <summary>
         /// 插入一个节点,带一属性
         /// </summary>
         /// <param name="MainNode"></param>
         /// <param name="Element"></param>
         /// <param name="Attrib"></param>
         /// <param name="AttribContent"></param>
         /// <param name="Content"></param>
         public void InsertElement(string MainNode, string Element, string Attrib, string AttribContent, string Content)
         {
             //插入一个节点,带一属性。 
             XmlNode objNode = objXmlDoc.SelectSingleNode(MainNode);
             XmlElement objElement = objXmlDoc.CreateElement(Element);
             objElement.SetAttribute(Attrib, AttribContent);
             objElement.InnerText = Content;
             objNode.AppendChild(objElement);
         }
         /// <summary>
         /// 插入一个节点,不带属性
         /// </summary>
         /// <param name="MainNode"></param>
         /// <param name="Element"></param>
         /// <param name="Content"></param>
         public void InsertElement(string MainNode, string Element, string Content)
         {
             XmlNode objNode = objXmlDoc.SelectSingleNode(MainNode);
             XmlElement objElement = objXmlDoc.CreateElement(Element);
             objElement.InnerText = Content;
             objNode.AppendChild(objElement);
         }




        #region xml操作 静态方法组=============
        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="attribute">属性名，非空时返回该属性值，否则返回串联值</param>
        /// <returns>string</returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.Read(path, "/Node", "")
         * XmlHelper.Read(path, "/Node/Element[@Attribute='Name']", "Attribute")
         ************************************************/
        public static string Read(string path, string node, string attribute)
        {
            if (path != "" && path.IndexOf(":") < 0) { path = System.Web.HttpContext.Current.Server.MapPath(path); } 

            string value = "";
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xn = doc.SelectSingleNode(node);
                value = (attribute.Equals("") ? xn.InnerText : xn.Attributes[attribute].Value);
            }
            catch { }
            return value;
        }

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="element">元素名，非空时插入新元素，否则在该元素中插入属性</param>
        /// <param name="attribute">属性名，非空时插入该元素属性值，否则插入元素值</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.Insert(path, "/Node", "Element", "", "Value")
         * XmlHelper.Insert(path, "/Node", "Element", "Attribute", "Value")
         * XmlHelper.Insert(path, "/Node", "", "Attribute", "Value")
         ************************************************/
        public static void Insert(string path, string node, string element, string attribute, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xn = doc.SelectSingleNode(node);
                if (element.Equals(""))
                {
                    if (!attribute.Equals(""))
                    {
                        XmlElement xe = (XmlElement)xn;
                        xe.SetAttribute(attribute, value);
                    }
                }
                else
                {
                    XmlElement xe = doc.CreateElement(element);
                    if (attribute.Equals(""))
                        xe.InnerText = value;
                    else
                        xe.SetAttribute(attribute, value);
                    xn.AppendChild(xe);
                }
                doc.Save(path);
            }
            catch { }
        }

        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="attribute">属性名，非空时修改该节点属性值，否则修改节点值</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.Insert(path, "/Node", "", "Value")
         * XmlHelper.Insert(path, "/Node", "Attribute", "Value")
         ************************************************/
        public static void Update(string path, string node, string attribute, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xn = doc.SelectSingleNode(node);
                XmlElement xe = (XmlElement)xn;
                if (attribute.Equals(""))
                    xe.InnerText = value;
                else
                    xe.SetAttribute(attribute, value);
                doc.Save(path);
            }
            catch { }
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="attribute">属性名，非空时删除该节点属性值，否则删除节点值</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.Delete(path, "/Node", "")
         * XmlHelper.Delete(path, "/Node", "Attribute")
         ************************************************/
        public static void Delete(string path, string node, string attribute)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xn = doc.SelectSingleNode(node);
                XmlElement xe = (XmlElement)xn;
                if (attribute.Equals(""))
                    xn.ParentNode.RemoveChild(xn);
                else
                    xe.RemoveAttribute(attribute);
                doc.Save(path);
            }
            catch { }
        }




        //string xml = Server.MapPath("/assets/config/system.config");
        //插入元素
        //XmlHelper.Insert(xml, "/Root", "Studio", "", "");
        //插入元素/属性
        //XmlHelper.Insert(xml, "/Root/Studio", "Site", "Name", "小路工作室");
        //XmlHelper.Insert(xml, "/Root/Studio", "Site", "Name", "丁香鱼工作室");
        //XmlHelper.Insert(xml, "/Root/Studio", "Site", "Name", "谱天城工作室");
        //XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "Master", "", "红尘静思");
        //插入属性
        //XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='小路工作室']", "", "Url", "http://www.wzlu.com/");
        //XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='丁香鱼工作室']", "", "Url", "http://www.luckfish.net/");
        //XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "", "Url", "http://www.putiancheng.com/");
        //修改元素值
        //XmlHelper.Update(xml, "/Root/Studio/Site[@Name='谱天城工作室']/Master", "", "RedDust");
        //修改属性值
        //XmlHelper.Update(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "Url", "http://www.putiancheng.net/");
        //XmlHelper.Update(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "Name", "PuTianCheng Studio");
        //读取元素值
        //Response.Write("<div>" + XmlHelper.Read(xml, "/Root/Studio/Site/Master", "") + "</div>");
        //读取属性值
        //Response.Write("<div>" + XmlHelper.Read(xml, "/Root/Studio/Site", "Url") + "</div>");
        //读取特定属性值
        //Response.Write("<div>" + XmlHelper.Read(xml, "/Root/Studio/Site[@Name='丁香鱼工作室']", "Url") + "</div>");
        //删除属性
        //XmlHelper.Delete(xml, "/Root/Studio/Site[@Name='小路工作室']", "Url");
        //删除元素
        //XmlHelper.Delete(xml, "/Root/Studio", "");

        #endregion ==========



    } 

}
